<template>
  <div class='esign-data-list'>
    <div class='fixed-search'>
      <div class='search-container'>
        <el-form :model='searchForm' ref='searchForm'>
          <!-- 第一行查询条件 -->
          <div class='search-row'>
            <el-form-item label='来源类型' class='search-item'>
              <el-select v-model='searchForm.direction' placeholder='请选择来源类型'>
                <el-option label='云商' value='0' />
                <el-option label='e签宝' value='1' />
              </el-select>
            </el-form-item>
            <el-form-item label='接口编码' class='search-item'>
              <el-input v-model='searchForm.interfaceCode' placeholder='请输入接口编码' clearable />
            </el-form-item>
            <el-form-item label='请求URL' class='search-item'>
              <el-input v-model='searchForm.url' placeholder='请输入请求URL' clearable />
            </el-form-item>
          </div>

          <!-- 第二行查询条件 -->
          <div class='search-row'>
            <el-form-item label='请求数据' class='search-item'>
              <el-input v-model='searchForm.requestBody' placeholder='请输入请求数据' clearable />
            </el-form-item>
            <el-form-item label='响应数据' class='search-item'>
              <el-input v-model='searchForm.responseBody' placeholder='请输入响应数据' clearable />
            </el-form-item>
            <el-form-item label='发送时间' class='search-item'>
              <el-date-picker
                v-model='searchForm.requestTimeRange'
                type='datetimerange'
                value-format='yyyyMMddHHmmss'
                format='yyyy-MM-dd HH:mm:ss'
                range-separator='至'
                start-placeholder='开始日期'
                end-placeholder='结束日期'
                :default-time="['00:00:00', '23:59:59']"
                style='width: 100%'
                :picker-options='pickerOptions'
                class='datetime-picker'
              />
            </el-form-item>
          </div>

          <!-- 查询按钮 -->
          <div class='search-buttons'>
            <el-button type='primary' @click='handleSearch' icon='el-icon-search'>查询</el-button>
            <el-button @click='resetSearch' icon='el-icon-refresh'>重置</el-button>
          </div>
        </el-form>
      </div>
    </div>

    <div class='table-container'>
      <el-table
        :data='tableData'
        border
        height='100%'
        v-loading='loading'
        style='width: 100%'
      >
        <el-table-column prop='index' label='序号' width='35' fixed />
        <el-table-column prop='interfaceCode' label='接口编码' width='70' />
        <el-table-column prop='desc' label='接口描述' width='100' />
        <el-table-column prop='requestMethod' label='请求方式' width='60' />
        <el-table-column prop='url' label='请求url' width='155' />
        <el-table-column prop='requestHeaders' label='请求头' width='305' />
        <el-table-column prop='requestBody' label='请求数据' width='280'>
          <template slot-scope='scope'>
            <el-popover
              placement='top-start'
              width='500'
              trigger='hover'
              popper-class='custom-popover'
            >
              <div class='popover-content'>
                <el-button
                  class='copy-btn'
                  size='mini'
                  type='primary'
                  @click='copyToClipboard(scope.row.requestBody)'
                >
                  复制
                </el-button>
                <div class='popover-text'>
                  {{ formatJsonForDisplay(scope.row.requestBody) }}
                </div>
              </div>
              <div class='json-cell' slot='reference'>
                {{ formatJsonForDisplay(scope.row.requestBody) }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop='sendTime' label='发送时间' width='151'>
          <template slot-scope='scope'>
            {{ formatTime(scope.row.sendTime) }}
          </template>
        </el-table-column>
        <el-table-column prop='resultCode' label='结果编码' width='75' />
        <el-table-column prop='resultMessage' label='结果消息' width='75' />
        <el-table-column prop='responseBody' label='响应数据' width='150'>
          <template slot-scope='scope'>
            <el-popover
              placement='top-start'
              width='500'
              trigger='hover'
              popper-class='custom-popover'
            >
              <div class='popover-content'>
                <el-button
                  class='copy-btn'
                  size='mini'
                  type='primary'
                  @click='copyToClipboard(scope.row.responseBody)'
                >
                  复制
                </el-button>
                <div class='popover-text'>
                  {{ formatJsonForDisplay(scope.row.responseBody) }}
                </div>
              </div>
              <div class='json-cell' slot='reference'>
                {{ formatJsonForDisplay(scope.row.responseBody) }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop='responseTime' label='响应时间' width='151'>
          <template slot-scope='scope'>
            {{ formatTime(scope.row.responseTime) }}
          </template>
        </el-table-column>
        <el-table-column prop='costTime' label='接口耗时(ms)' width='60' />
      </el-table>
    </div>

    <div class='pagination-container'>
      <el-pagination
        @size-change='handleSizeChange'
        @current-change='handleCurrentChange'
        :current-page='pagination.pageNo'
        :page-sizes='[10, 20, 50, 100]'
        :page-size='pagination.pageSize'
        layout='total, sizes, prev, pager, next, jumper'
        :total='pagination.total'
      />
    </div>
  </div>
</template>

<script>
import { queryEsignLog } from '@/api/apilog/apilog';

export default {
  name: 'EsignDataList',
  data() {
    const now = new Date();
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(now.getDate() - 7);

    return {
      searchForm: {
        direction: '0',
        interfaceCode: '',
        url: '',
        requestBody: '',
        responseBody: '',
        requestTimeRange: [
          this.formatDate(oneWeekAgo, 'yyyyMMdd') + '000000',
          this.formatDate(now, 'yyyyMMdd') + '235959',
        ],
      },
      tableData: [],
      loading: false,
      pagination: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 日期格式化方法
    formatDate(date, fmt) {
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
          );
        }
      }
      return fmt;
    },
    async fetchData() {
      this.loading = true;

      const params = {
        direction: this.searchForm.direction,
        interfaceCode: this.searchForm.interfaceCode,
        url: this.searchForm.url,
        requestBody: this.searchForm.requestBody,
        responseBody: this.searchForm.responseBody,
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
      };

      // 处理时间范围
      if (this.searchForm.requestTimeRange && this.searchForm.requestTimeRange.length === 2) {
        params.sendTimeStart = this.searchForm.requestTimeRange[0];
        params.sendTimeEnd = this.searchForm.requestTimeRange[1];
      } else {
        params.sendTimeStart = '';
        params.sendTimeEnd = '';
      }

      try {
        const response = await queryEsignLog(params);
        this.tableData = response.data.list.map((item, index) => ({
          ...item,
          index: (this.pagination.pageNo - 1) * this.pagination.pageSize + index + 1,
        }));
        this.pagination.total = response.data.total;
      } catch (error) {
        this.$message.error(error.message || '请求失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.pagination.pageNo = 1;
      this.fetchData();
    },
    resetSearch() {
      // 重置时仍然保持最近一周的时间范围
      const now = new Date();
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(now.getDate() - 7);

      this.searchForm = {
        direction: '0',
        interfaceCode: '',
        url: '',
        requestBody: '',
        responseBody: '',
        requestTimeRange: [
          this.formatDate(oneWeekAgo, 'yyyyMMdd') + '000000',
          this.formatDate(now, 'yyyyMMdd') + '235959',
        ],
      };
      this.pagination.pageNo = 1;
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.pagination.pageNo = val;
      this.fetchData();
    },
    formatTime(timeStr) {
      if (!timeStr) return '';
      // 格式化为 YYYY-MM-DD HH:mm:ss
      return `${timeStr.substr(0, 4)}-${timeStr.substr(4, 2)}-${timeStr.substr(6, 2)} ${timeStr.substr(
        8,
        2,
      )}:${timeStr.substr(10, 2)}:${timeStr.substr(12, 2)}`;
    },
    formatJsonForDisplay(json) {
      if (!json) return '';
      try {
        // 如果已经是字符串形式的JSON，先解析
        const parsed = typeof json === 'string' ? JSON.parse(json) : json;
        // 然后格式化为易读的字符串
        return JSON.stringify(parsed, null, 2);
      } catch (e) {
        // 如果不是JSON格式，直接返回
        return json;
      }
    },
    copyToClipboard(text) {
      let textToCopy;
      try {
        // 尝试解析为JSON对象
        const jsonObj = typeof text === 'string' ? JSON.parse(text) : text;
        // 格式化为易读的JSON字符串
        textToCopy = JSON.stringify(jsonObj, null, 2);
      } catch (e) {
        // 如果不是JSON格式，直接使用原始文本
        textToCopy = text;
      }
      const textarea = document.createElement('textarea');
      textarea.value = textToCopy;
      textarea.style.position = 'fixed'; // 防止页面滚动
      textarea.style.left = '0';
      textarea.style.top = '0';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();

      try {
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('格式化JSON已复制到剪贴板');
        } else {
          this.$message.error('复制失败');
        }
      } catch (err) {
        this.$message.error('复制失败: ' + err);
      }

      document.body.removeChild(textarea);
    },
  },
};
</script>

<style lang='scss' scoped>
.esign-data-list {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
}

.fixed-search {
  background: white;
  z-index: 10;
  flex-shrink: 0;

  .search-container {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .search-row {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
    }

    .search-item {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 15px;
      flex: 1;
      min-width: 350px;
      max-width: 500px;

      ::v-deep .el-form-item__label {
        width: 120px;
        text-align: right;
        padding-right: 10px;
        flex-shrink: 0;
      }

      ::v-deep .el-form-item__content {
        flex: 1;
        min-width: 200px;
      }
    }

    .search-buttons {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
  border-radius: 4px;

  ::v-deep .el-table {
    flex: 1;
    width: 100%;

    .el-table__body-wrapper {
      overflow-y: auto !important;
    }

    .cell {
      white-space: pre-line;
      word-break: break-all;
    }

    .json-cell {
      max-width: 400px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }
  }


  .pagination-container {
    padding: 20px 0;
    text-align: right;
    flex-shrink: 0;
  }
}

.custom-popover {
  max-width: 500px !important;
  max-height: 300px;
  overflow: auto;
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 10px;

  .popover-content {
    position: relative;

    .copy-btn {
      position: absolute;
      right: 5px;
      top: -30px;
      z-index: 10;
    }

    .popover-text {
      margin-top: 20px;
      padding-right: 40px;
    }
  }
}
</style>

